// APP
if (window.plus) {
    verfiyAccountModelReady();
} else {
    document.addEventListener('plusready', verfiyAccountModelReady, false);
}
// Web
$(function () {
    if (AGENT_CLIENT.WEB) {
        verfiyAccountModelReady();
    }
})
var verfiyAccountModel = function () {
}

function verfiyAccountModelReady() {
    var _backurl = getUrlParam("backurl");
    var _fromurl = getUrlParam("fromurl");
    verfiyAccountModel = function () {
    };
    verfiyAccountModel.prototype = {
        // 用户登录
        userlogin: function (username, password) {
            var model = this;
            //记住登陆账号
            clearUserLocalStorage(username);
            setLocalStorage(STORAGE_MANAGER.username, username);
            var postData = {
                "username": username /* "tony@iapp.hk"*/,
                "password": password /*"123456"*/,
                "ip": $.getIPAddress()
            };

            $.ajax({
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/account/login",
                async: true,
                data: postData,
                beforeSend: function () {
                    $.showWaiting("登录中...");
                }
            }).done(function (data) {
                model.loadmember(data);
            }).fail(function (data) {
                if (data && data.responseText) {
                    var response = JSON.parse(data.responseText);
                    $.alert(response.Message);
                } else {
                    $.alert("登录失败");
                }
            }).always(function () {
                $.closeWaiting();
            });


        },
        // 获取会员信息
        loadmember: function (userinfo) {
            removeLocalStorage(STORAGE_MANAGER.user);
            setLocalStorage(STORAGE_MANAGER.user, userinfo);
            var model = this;
            
            $.ajax({
                headers: { "token": userinfo.token },
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/member/" + userinfo.id
            }).done(function (data) {
                setLocalStorage(STORAGE_MANAGER.currentmember, data);
                model.backRedirect();
            });
            //登录后计算购物车所有商品数量
            $.ajax({
            	type: "GET",
            	headers:{ token: userinfo.token },
            	url: CONFIG_MANAGER.RequstUrl + "v1/cart/sum/" + userinfo.id,
            	async:true,
            }).done(function(data){
            	console.log( JSON.stringify(data) );
            	setLocalStorage(STORAGE_MANAGER.cacheproductcount, data.count);
            	if(AGENT_CLIENT.APP){
            		plus.webview.getWebviewById("../home/main.html").evalJS("getShopcartProductCount()");
            	}
            });
        },
        // 第三方用户登录验证
        verifyAccount: function (userinfo) {
            var model = this;
            var postdata = {
                type: userinfo.typeid,
                id: userinfo.openid,
                name: userinfo.name,
                org: 6010,
                ip: $.getIPAddress()
            };
            console.log("postdata:" + JSON.stringify(postdata));
            $.ajax({
                headers: {
                    'Content-Type': 'application/json'
                },
                type: 'POST',
                url: CONFIG_MANAGER.RequstUrl + "v1/account/third/login",
                data: JSON.stringify(postdata),
                dataType: "json"
            }).done(function (res) {
                model.loadmember(res);
            }).fail(function (res) {
            	$.toast(res.responseJSON.message);
                if (res && res.responseJSON.message.indexOf("未注册") > -1) {
                    // 未关联该账号，注册
                    setPageParams(PAGE_NAME.account_bindaccount, {
                        typeid: userinfo.typeid,
                        mainid: -1,
                        openid: userinfo.openid,
                        name: userinfo.name
                    });
                    console.log("message:" + JSON.stringify(res.responseJSON));
                    redirect("../account/bindaccount.html");
                } else {
                    $.alert(res.responseJSON.message);
                }
            }).always(function () {
                $.closeWaiting();
            });
        },
        // 登录成功回跳转
        backRedirect: function () {
          if (AGENT_CLIENT.APP) {
            // 刷新我的生活
            var mylifeWebView = plus.webview.getWebviewById("../mine/mylife.html");
            if (mylifeWebView) {
                mylifeWebView.evalJS("reloadPage()");
            }

            // 刷新星粉星币
            var coinlistWebView = plus.webview.getWebviewById("../coin/coinlist.html");
            if (coinlistWebView) {
                coinlistWebView.evalJS("reloadPage()");
            }

            // 刷新购物车
            var shopcartWebView = plus.webview.getWebviewById("../shopcart/shoppingcart.html");
            if (shopcartWebView) {
                shopcartWebView.evalJS("reloadPage()");
            }
          }
          if (_backurl && _backurl.indexOf("login.html") > -1) {
              _backurl = null;
          }
          if (_backurl) {
            // 解决安卓无法处理../ 问题
            _backurl = "../" + _backurl.replace('|', "/");
            if (AGENT_CLIENT.APP) {
              var homePages = {
                "../home/main.html": -1,
                '../home/index.html': 0,
                '../home/classification.html': 1,
                '../coin/coinlist.html': 2,
                '../shopcart/shoppingcart.html': 3,
                '../mine/mylife.html': 4,
                '../account.html': 4
              };
              //我的关注，星粉联
              if (undefined != homePages[_backurl] && homePages[_backurl] != -1) {
                plus.webview.getWebviewById("../home/main.html").evalJS("redirectTab(" + homePages[_backurl] + ")");
                plus.webview.currentWebview().close();
              } else {
                if(_fromurl){
                	_backurl += ((_backurl.indexOf("?")>-1)?"&fromurl=":"?fromurl=") + _fromurl;
                }
                redirect(_backurl, false, "pop-out", function () {
                    plus.webview.currentWebview().close();
                }); 
              }
            } else {
              if(_fromurl){
              	_backurl += ((_backurl.indexOf("?")>-1)?"&fromurl=":"?fromurl=") + _fromurl;
              }
							redirect(_backurl);
            }
        } else {            	
					if (AGENT_CLIENT.APP) {
						plus.webview.getWebviewById("../mine/mylife.html").evalJS("reloadPage()");
						plus.webview.getWebviewById("../home/main.html").evalJS("redirectTab(4)");					
					} else{
						redirect("../mine/mylife.html");
					}
        }
      }
    };
}